package myexchange

class ExchangeService {

    static transactional = true
	
	GameService gameService

    boolean tradeShare(long playerId,Share share,int quantity) throws ExchangeException {
		
		Player player = Player.get(playerId)
		int sharePrice = share.price;
    	int playerCash = player.cash;
		
		if (quantity > 0){ //buy
			//check if player has enough cash
//			if (sharePrice * quantity > playerCash){
//				throw new ExchangeException("Player doesn't have enough cash for this transaktion");
//				return false;
//			}
		}		
		
		//buy or sell shares for the player
		def exchangeList = Exchange.findAllByPlayerAndShare(player,share)
		if (exchangeList?.size == 1){ //player already owns this share 
			Exchange exchangeInstance = exchangeList[0]
			int oldQuantity = exchangeList[0].quantity;
			int newQuantity = oldQuantity + quantity;
			if (newQuantity < 0){ //player is not owning so much shares
				throw new ExchangeException("Player doesn't have enought quantity of this share");
				return false;
			}
			exchangeInstance.quantity = newQuantity;
			exchangeInstance.save();
			player.cash -= sharePrice * quantity;
			player.save(); 
		}else if((exchangeList?.size == 0)){ //player did not had this share
			new Exchange([player:player,share:share,quantity:quantity]).save(failOnError: true); 
			player.cash -= sharePrice * quantity;
			player.save();
		}else{	//should never happen
			return false;
		}
		String note = "${(quantity>0)?'purchased':'sold'} $quantity share(s) of ${share}"
		gameService.addHistory(note,player)
		
		return true;
    }
}
